package com.milk.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milk.constant.MessageConstant;
import com.milk.context.BaseContext;
import com.milk.dto.UserLoginDTO;
import com.milk.entity.User;
import com.milk.entity.UserSignIn;
import com.milk.exception.UserNotLoginException;
import com.milk.mapper.UserMapper;
import com.milk.mapper.UserSignInMapper;
import com.milk.properties.WeChatProperties;
import com.milk.service.UserService;
import com.milk.utils.HttpClientUtil;
import com.milk.vo.UserVO;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 刘英豪
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private static final String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatProperties weChatProperties;
    @Autowired
    private UserSignInMapper userSignInMapper;


    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //调用微信接口获取OpenId

        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");

        String json = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        //判断是否获取到了OpenId 没有抛出异常
        if (openid==null){
            throw new UserNotLoginException(MessageConstant.LOGIN_FAILED);
        }
        //判断是否是新用户
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("openid",openid);
        User user = userMapper.selectOne(qw);

        //如果新用户，完成注册
        if (user==null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .integral(0.0)
                    .build();
            userMapper.insert(user);
        }
        return user;
    }

    /**
     * 查询个人信息
     * @return
     */
    public UserVO selectInfo() {
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);

        QueryWrapper<UserSignIn> qw = new QueryWrapper<>();
        qw.eq("user_id",userId);
        UserSignIn userSignIn = userSignInMapper.selectOne(qw);
        LocalDateTime updatetime = userSignIn.getUpdatetime();
        int status ;
        if (updatetime != null && updatetime.toLocalDate().equals(LocalDate.now())){
            status = 1;
            userVO.setConsecutiveDays(userSignIn.getConsecutiveDays());
        }else {
            status = 0;
            userVO.setConsecutiveDays(0);
            userSignIn.setConsecutiveDays(0);
            userSignInMapper.updateById(userSignIn);
        }
        userVO.setStatus(status);
        return userVO;
    }

    /**
     * 修改个人信息
     * @param user
     */
    public void updateUser(User user) {
        userMapper.updateById(user);
    }

}
